#include "dtkserialportdeal.h"
#include <QDebug>

struct BaudAndParity {
    BaudRateType rate;
    ParityType   parity;
};

static BaudAndParity BPList[24] = {
    {BAUD1200,PAR_NONE},{BAUD2400,PAR_NONE},{BAUD4800,PAR_NONE},{BAUD9600,PAR_NONE},
    {BAUD19200,PAR_NONE},{BAUD38400,PAR_NONE},{BAUD57600,PAR_NONE},{BAUD115200,PAR_NONE},

    {BAUD1200,PAR_EVEN},{BAUD2400,PAR_EVEN},{BAUD4800,PAR_EVEN},{BAUD9600,PAR_EVEN},
    {BAUD19200,PAR_EVEN},{BAUD38400,PAR_EVEN},{BAUD57600,PAR_EVEN},{BAUD115200,PAR_EVEN},

    {BAUD1200,PAR_ODD},{BAUD2400,PAR_ODD},{BAUD4800,PAR_ODD},{BAUD9600,PAR_ODD},
    {BAUD19200,PAR_ODD},{BAUD38400,PAR_ODD},{BAUD57600,PAR_ODD},{BAUD115200,PAR_ODD}
};

DTKSerialPortDeal::DTKSerialPortDeal(QWidget *zigbeeImple):mImple(zigbeeImple) {
    DtkSerialDev = new Win_QextSerialPort(); //定义串口对象
    SerialOpenState = FFALSE;
}

DTKSerialPortDeal::~DTKSerialPortDeal() {
    delete DtkSerialDev;
}

_S32 DTKSerialPortDeal::OpenServialDevice(QString comName,BaudRateType baudRate,ParityType parity) {

    DtkSerialDev->setPortName(comName);
    DtkSerialDev->setQueryMode(QextSerialBase::Polling);
    if(!DtkSerialDev->open(QIODevice::ReadWrite))  //打开串口
    {
        qDebug("[QtTRBCSerialPort] open %s fail!\n",qPrintable(comName));
        return FAILURE;
    }
    DtkSerialDev->setBaudRate(baudRate);     //设置波特率
    DtkSerialDev->setDataBits(DATA_8);         //设置数据位
    DtkSerialDev->setParity(parity);         //设置奇偶校验
    DtkSerialDev->setStopBits(STOP_1);         //设置停止位
    DtkSerialDev->setFlowControl(FLOW_OFF);    //设置数据流控制，我们使用无数据流控制的默认设置
    DtkSerialDev->setTimeout(50);             //设置延时100到50

    SerialOpenState = FTRUE;
    return SUCCESS;
}

_S32 DTKSerialPortDeal::WriteServialDevice(_CHAR* data, _U64 Length) {

    qDebug("[WriteServialDevice] data length:%u \n",(_U32)Length);
    for (_U64 i = 0;i<Length;i++) {
        qDebug("%#x,",data[i]);
    }
    qDebug("[WriteServialDevice] data end!");

    if (SerialOpenState)
    {
        DtkSerialDev->write(data,Length);
        return SUCCESS;
    }
    return FAILURE;
}

_S32 DTKSerialPortDeal::ReadServialDevice(_CHAR* data, _U64 Length) {

    if (SerialOpenState)
    {
        return DtkSerialDev->read(data,Length); //读到的值返回给data
    }

   return FAILURE;
}

_S32 DTKSerialPortDeal::CloseServialDevice() {
    DtkSerialDev->close();
    SerialOpenState = FFALSE;
    return SUCCESS;
}
